<?php

namespace Library\Route;

/**
 * 本类用来操作路由
 * Class Route
 * @package Library\Route
 */
class Route implements RouteInterface
{

    /**
     * 用来装载所有的路由配置
     * @var array
     */
    public static  $routes = [];

    public static $http_error_no = 404;

    /**
     * 引入路由配置文件
     * 并解析返回该路由的绝对路径
     * 如果没有找到会返回404
     * 如果不符合匹配会返回警告
     * @param $url
     * @param array $params
     * @return bool | string
     * @throws \ErrorException
     */
    public static function forward($url, array $params = [])
    {
        if(!array_key_exists($url, self::$routes)) {
            // 404
            self::$http_error_no = 404;
            return false;
        } else {
            if(RouteChecker::check_http_method($_SERVER['REQUEST_METHOD'], self::$routes[$url]['method'])) {
                if(RouteChecker::check_pattern($params, self::$routes[$url]['pattern'])) {
                    $callback = self::$routes[$url]['callback'];
                    if(RouteChecker::check_callback_closure($callback)) {
                        // 执行回调
                        $callback();
                    }
                } else {
                    throw new \Exception('传输数据不符合表达式,参数有误');
                }


                // todo register_shutdown_function();

            } else {
                // or 404
                throw new \ErrorException('错误的请求方式,你需要使用('.self::$routes[$url]['method'] . ')');
            }

        }
    }


    /**
     * 兼容的请求方式
     * @param $route
     * @param array $pattern
     * @param string $function
     * @param string $method
     * @throws \ErrorException
     */
    public static function any($route, array $pattern = [],  $function = '', $method = '')
    {
        if(RouteChecker::check_route($route)) {
            if(!in_array(strtolower($method), ['get', 'post', 'push', 'delete', ''])) {
                throw new \ErrorException('请求路由时, 请求方法有误');
            }
            self::$routes[$route] = [
                "pattern"   => $pattern,
                "method"    => $method,
            ];

            if($function instanceof \Closure) {

                self::$routes[$route]["callback"] = $function;
            }

        } else {
            throw new \ErrorException('路由不符合标准');
        }
    }

    /**
     * 只允许GET方法
     * @param $route
     * @param array $pattern
     * @param string $function
     */
    public static function get($route, array $pattern = [], $function = '')
    {
        $method = 'get';
        self::any($route, $pattern, $function, $method);
        unset($method);
    }

    /**
     * 只允许POST方法
     * @param $route
     * @param array $pattern
     * @param string $function
     */
    public static function post($route, array $pattern = [], $function = '')
    {
        $method = 'post';
        self::any($route, $pattern, $function, $method);
        unset($method);
    }



}
